﻿// <copyright file="NeutralKingsCollector.cs" company="Ecole Normale Supérieure">
// Released under GPLv2
// </copyright>
// <summary>Contains a scheduled service which eliminates squares with dead kings.</summary>

namespace Sqwarea.Batch
{
    using System;
    using System.Linq;
    using Lokad.Cloud.ServiceFabric;
    using Lokad.Cloud.Services;
    using Lokad.Cloud.Storage;
    using Sqwarea.Persistence;
    
    /// <summary>
    /// A daemon that checks every king for dead ones and revert their square to neutral when necessary.
    /// </summary>
    [ScheduledServiceSettings(
        AutoStart = true,
        ProcessingTimeoutSeconds = GlobalParameters.NeutralKingsCollectorTimeOutSeconds,
        TriggerInterval = GlobalParameters.NeutralKingsCollectorIntervalSecond)]
    public class NeutralKingsCollector : ScheduledService
    {
        /// <summary>
        /// Gets or sets the game provider used by this service
        /// </summary>
        public IGameProvider GameProvider { get; set; }

        /// <summary>
        /// Scheduled run of elimination of neutral king squares
        /// </summary>
        protected override void StartOnSchedule()
        {
            //// First we filter out deadkings.
            var deadkings = from k in this.GameProvider.GetAllKings()
                               where k.OpenId == null
                               select k;

            //// Then, we check dead kings that still appears on the board.
            foreach (King k in deadkings)
            {
                var sq = this.GameProvider.GetSquareByPosition(k.Position);
                King k1 = k;
                this.GameProvider.UpdateSquare(
                    sq.Position,
                    s =>
                    {
                        var s1 = s;
                        s1.HasKing = false;
                        s1.KingId = King.NeutralKingId;
                        if (s.HasKing && (s.KingId == k1.Id) && (k1.OpenId == null))
                        {
                            return s1;
                        }

                        return s;
                    });
            }
        }
    }
}
